<template>
  <div class="console-panel">
    <div class="console-header">
      <h4>控制台</h4>
      <el-button size="small" @click="handleClear">清空</el-button>
    </div>
    <div class="console-content" ref="consoleContentRef">
      <div
        v-for="(log, index) in logs"
        :key="index"
        :class="['console-log', `console-${log.type}`]"
      >
        <span class="log-type">[{{ log.type }}]</span>
        <span class="log-message">{{ log.message }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'

export interface ConsoleLog {
  type: 'log' | 'error' | 'warn' | 'info'
  message: string
}

interface Props {
  logs: ConsoleLog[]
}

interface Emits {
  (e: 'clear'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const consoleContentRef = ref<HTMLDivElement | null>(null)

// 当日志更新时，自动滚动到底部
watch(() => props.logs.length, () => {
  nextTick(() => {
    if (consoleContentRef.value) {
      consoleContentRef.value.scrollTop = consoleContentRef.value.scrollHeight
    }
  })
})

const handleClear = () => {
  emit('clear')
}
</script>

<style lang="scss" scoped>
.console-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #1e1e1e;
  border-radius: 4px;
  overflow: hidden;

  .console-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    background-color: #252526;
    border-bottom: 1px solid #3c3c3c;

    h4 {
      margin: 0;
      color: #cccccc;
      font-size: 14px;
    }
  }

  .console-content {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    font-family: 'Consolas', 'Monaco', monospace;
    font-size: 13px;

    .console-log {
      padding: 4px 0;
      line-height: 1.6;

      .log-type {
        font-weight: bold;
        margin-right: 8px;
      }

      .log-message {
        word-break: break-word;
      }

      &.console-log {
        color: #cccccc;
        .log-type {
          color: #4ec9b0;
        }
      }

      &.console-error {
        color: #f48771;
        .log-type {
          color: #f14c4c;
        }
      }

      &.console-warn {
        color: #cca700;
        .log-type {
          color: #cca700;
        }
      }

      &.console-info {
        color: #3794ff;
        .log-type {
          color: #3794ff;
        }
      }
    }
  }
}
</style>

